<template>
  <!-- 对账管理汇总列表 -->
  <div >
    <div v-show="!showCustomerDetail && !showCarrierDetail">
      <div class="allOrderContainer" v-if="activeName === 'first'">
        <!-- <div class="shareContainer"> -->
          <div class="searchContainer">
            <el-form ref="form" :model="searchCustomerData" :inline="true">
              <el-form-item label="客户名称" size="mini" style="width: 270px">
                <el-select
                  filterable
                  @focus="getCustomerList"
                  v-model="searchCustomerData.customer_id"
                  style="width: 200px"
                >
                  <el-option
                    v-for="customer in customerList"
                    :key="customer.id"
                    :label="customer.name"
                    :value="customer.id"
                  />
                </el-select>
              </el-form-item>
              <!-- 默认上月一号到上月最后一天,最多不超过三个月 -->
              <el-form-item label="创建时间" size="mini" style="width: 290px">
                <el-date-picker
                  v-model="searchCustomerData.createTime"
                  type="daterange"
                  value-format="timestamp"
                  align="right"
                  unlink-panels
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="pickerOptions"
                  :default-time="['00:00:00', '23:59:59']"
                  style="width: 220px"
                />
              </el-form-item>
              <el-form-item
                label="客户所属区域"
                size="mini"
                style="width: 300px"
              >
                <el-select
                  filterable
                  @focus="getBigAreaList"
                  v-model="searchCustomerData.bigArea"
                  style="width: 200px"
                >
                  <el-option
                    v-for="bigArea in bigAreaList"
                    :key="bigArea.id"
                    :label="bigArea.name"
                    :value="bigArea.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                label="客户所属销售"
                size="mini"
                style="width: 300px"
              >
                <el-select
                  @focus="getSalesList"
                  filterable
                  v-model="searchCustomerData.sales"
                  style="width: 200px"
                >
                  <el-option
                    v-for="sales in salesList"
                    :key="sales.id"
                    :label="sales.nickname"
                    :value="sales.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item size="mini">
                <el-button
                  type="primary"
                  data-tracker="P48-1"
                  icon="el-icon-search"
                  @click="searchCheckList"
                  >查询</el-button
                >
                <el-button
                  plain
                  icon="el-icon-refresh-left"
                  data-tracker="P48-2"
                  @click="resettingData"
                  >重置</el-button
                >
              </el-form-item>
            </el-form>
          </div>
          <el-table
            :max-height="maxheight"
            ref="multipleTable"
            :row-key="(item) => item.customer_id"
            :data="customerTableData"
            border
            align="center"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              type="selection"
              width="45"
              :reserve-selection="true"
            >
            </el-table-column>
            <el-table-column
              prop=""
              fixed
              label="序号"
              width="50"
              type="index"
            ></el-table-column>
            <el-table-column
              prop="customer_name"
              fixed
              label="客户名称"
              width="220"
            >
              <template slot-scope="scope">
                <!-- 点击明细带上客户id和订单创建时间区间 -->
                <div
                  data-tracker="P48-3"
                  @click="
                    clickToDetail(
                      scope.row.customer_id,
                      scope.row.branch_id,
                      searchCustomerData.createTime
                    )
                  "
                  style="cursor: pointer; color: blue"
                >
                  {{ scope.row.customer_name }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="customer_type" label="客户类型" width="150">
              <template slot-scope="scope">
                {{ scope.row.customer_type === "0" ? "公司" : "个人" }}
              </template>
            </el-table-column>
            <el-table-column prop="branch_name" label="所属区域" width="220">
            </el-table-column>
            <el-table-column prop="total" label="总金额" width="150">
            </el-table-column>
            <el-table-column prop="al_total" label="已对账金额" width="150">
            </el-table-column>
            <el-table-column prop="un_total" label="未对账金额" width="150">
            </el-table-column>
            <el-table-column prop="belong_name" label="所属销售" width="150">
            </el-table-column>
            <el-table-column prop="count" label="总单数" width="80">
            </el-table-column>
          </el-table>
          <div class="operation">
            <el-pagination
              background
              @size-change="handleSizeChange1"
              @current-change="handleCurrentChange1"
              :current-page="pageNum1"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="pageSize1"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalListNum1"
            >
            </el-pagination>
          </div>
        <!-- </div> -->
      </div>
      <div class="allOrderContainer" v-if="activeName === 'second'">
        <!-- <div class="shareContainer"> -->
          <div class="searchContainer">
            <el-form ref="form" :model="searchCarrierData" :inline="true">
              <el-form-item label="承运商名称" size="mini" style="width: 290px">
                <el-select
                  filterable
                  @focus="getCarrierList"
                  v-model="searchCarrierData.carrier_id"
                  style="width: 200px"
                >
                  <el-option
                    v-for="carrier in carrierList"
                    :key="carrier.id"
                    :label="carrier.name"
                    :value="carrier.id"
                  />
                </el-select>
              </el-form-item>
              <!-- 默认上月一号到上月最后一天,最多不超过三个月 -->
              <el-form-item label="创建时间" size="mini" style="width: 300px">
                <el-date-picker
                  v-model="searchCarrierData.createTime"
                  type="daterange"
                  value-format="timestamp"
                  align="right"
                  unlink-panels
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="pickerOptions"
                  :default-time="['00:00:00', '23:59:59']"
                  style="width: 220px"
                />
              </el-form-item>
              <!-- <el-form-item
                  label="承运商所属区域"
                  size="mini"
                  style="width: 320px"
                >
                  <el-select
                    filterable
                    v-model="searchCarrierData.bigArea"
                    style="width: 200px"
                  >
                    <el-option
                      v-for="bigArea in bigAreaList"
                      :key="bigArea.id"
                      :label="bigArea.name"
                      :value="bigArea.id"
                    />
                  </el-select>
                </el-form-item> -->
              <el-form-item size="mini">
                <el-button
                  type="primary"
                  data-tracker="P48-5"
                  icon="el-icon-search"
                  @click="searchCheckList"
                  >查询</el-button
                >
                <el-button
                  plain
                  icon="el-icon-refresh-left"
                  data-tracker="P48-6"
                  @click="resettingData"
                  >重置</el-button
                >
              </el-form-item>
            </el-form>
          </div>
          <el-table
            :max-height="maxheight"
            ref="multipleTable"
            :data="carrierTableData"
            :row-key="(item) => item.carrier_id"
            border
            align="center"
            @selection-change="handleSelectionChange"
            style="width: 1367px"
          >
            <el-table-column
              type="selection"
              width="45"
              :reserve-selection="true"
            >
            </el-table-column>
            <el-table-column
              prop=""
              fixed
              label="序号"
              width="50"
              type="index"
            ></el-table-column>
            <el-table-column
              prop="carrier_name"
              fixed
              label="承运商名称"
              width="320"
            >
              <template slot-scope="scope">
                <!-- 点击明细带上客户id和订单创建时间区间 -->
                <div
                  data-tracker="P48-7"
                  @click="
                    clickToDetail(
                      scope.row.carrier_id,
                      scope.row.carrier_id,
                      searchCarrierData.createTime
                    )
                  "
                  style="cursor: pointer; color: blue"
                >
                  {{ scope.row.carrier_name }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="total" label="总金额" width="250">
            </el-table-column>
            <el-table-column prop="al_total" label="已对账金额" width="250">
            </el-table-column>
            <el-table-column prop="un_total" label="未对账金额" width="250">
            </el-table-column>
            <el-table-column prop="count" label="总单数" width="200">
            </el-table-column>
          </el-table>
          <div class="operation">
            <el-pagination
              background
              @size-change="handleSizeChange2"
              @current-change="handleCurrentChange2"
              :current-page="pageNum2"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="pageSize2"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalListNum2"
            >
            </el-pagination>
          </div>
        <!-- </div> -->
      </div>
    </div>
    <div class="checkContainer" v-show="showCustomerDetail" :key="activeName">
      <customerDetailList
        :customer_id="customer_detail_no"
        :bigArea="bigArea_detail_no"
        :createTime="customer_detail_time"
        :changeCustomerDetailPage="changeCustomerDetailPage"
      ></customerDetailList>
    </div>
    <div class="checkContainer" v-show="showCarrierDetail" :key="activeName">
      <carrierDetailList
        :carrier_id="carrier_detail_no"
        :createTime="carrier_detail_time"
        :changeCarrierDetailPage="changeCarrierDetailPage"
      ></carrierDetailList>
    </div>
  </div>
</template>

<script>
import customerDetailList from "./customerDetailList.vue";
import carrierDetailList from "./carrierDetailList.vue";
import pagination from "@/components/pagination";
import { reqCustomerSummaryList, reqCarrierSummaryList } from "@/api/finance";
import { setToken, getToken } from "@/utils/auth";
import { isHavePermission } from "@/utils/mUtils";

export default {
  data() {
    return {
      activeName: "first",
      showCustomerDetail: false, //是否展示客户列表详情
      showCarrierDetail: false, //是否展示承运商列表详情
      customerList: [], //客户列表
      bigAreaList: [], //区域列表
      salesList: [], //销售列表
      searchCustomerData: {
        customer_id: "", //客户名称
        createTime: [
          new Date().setTime(new Date().getTime() - 3600 * 1000 * 24 * 30),
          new Date().getTime(),
        ], //订单创建时间
        bigArea: "", //客户所属区域
        sales: "", // 客户所属销售
      }, //查询条件
      carrierList: [], //承运商列表
      searchCarrierData: {
        carrier_id: "", //承运商名称
        createTime: [
          new Date().setTime(new Date().getTime() - 3600 * 1000 * 24 * 30),
          new Date().getTime(),
        ], //订单创建时间
        bigArea: "", //承运商所属区域
        sales: "", // 承运商所属销售
      }, //查询条件
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      pageNum1: 1, //目前在第几页
      totalListNum1: 100, //列表总数
      pageSize1: 20, //一页多少条
      pageNum2: 1, //目前在第几页
      totalListNum2: 100, //列表总数
      pageSize2: 20, //一页多少条
      customerTableData: [], //客户列表数据
      carrierTableData: [], //承运商列表数据
      selectedOrders: [], //选中的条目的id组成的数组
      selectedDetails: [], //选中的条目的详情
      // otherInfo: {}, //对账单的其他信息
      operationType: false, //true是详情,false是修改
      // checkCategory: 0, //打开哪个对账页面
      // detailsTime: [], //明细运单的开单时间,要给传给check组件
      maxheight: "auto",
      customer_detail_no: "", //客户详情id
      bigArea_detail_no: "", //客户详情区域
      customer_detail_time: "", //客户详情时间段
      carrier_detail_no: "", //承运商详情id
      carrier_detail_time: "", //承运商详情时间段
    };
  },
  components: {
    pagination,
    customerDetailList,
    carrierDetailList,
  },
  mounted() {
    this.lastMonthTimetamp();
    if (this.$store.getters.customerList.length === 0) {
      this.$store.dispatch("getCustomerList");
    }
    if (this.$store.getters.websiteList.length === 0) {
      this.$store.dispatch("getWebsiteList");
    }
    if (this.$store.getters.adminList.length === 0) {
      this.$store.dispatch("getAdminList");
    }
    if (this.$store.getters.carrierList.length === 0) {
      this.$store.dispatch("getCarrierList");
    }
    this.displayOrders();
  },
  watch: {
    $route: {
      handler(newV, oldV) {
        if (this.$route.query.type == 0) {
          this.activeName = "first";
          this.displayOrders();
          this.showCarrierDetail = false;
        } else if (this.$route.query.type == 1) {
          this.activeName = "second";
          this.displayOrders();
          this.showCustomerDetail = false;
        }
        // console.log(this.$route.query.type, "this.$route.query.type");
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    async displayOrders() {
      const {
        pageNum1,
        pageSize1,
        pageSize2,
        pageNum2,
        searchCustomerData,
        searchCarrierData,
      } = this;
      if (this.activeName === "first") {
        let result = await reqCustomerSummaryList({
          branch_id: String(searchCustomerData.bigArea), //区域
          customer_id: String(searchCustomerData.customer_id), //客户
          belong_id: String(searchCustomerData.sales), //销售
          start_time: String(parseInt(searchCustomerData.createTime[0] / 1000)),
          end_time: String(parseInt(searchCustomerData.createTime[1] / 1000)),
          page: String(pageNum1),
          page_size: String(pageSize1),
        });
        if (result.code === 10000) {
          // // console.log("刷新客户列表");
          this.customerTableData = result.data.data || [];
          if (this.customerTableData.length > 6) {
            //两排操作栏
            this.maxheight = document.documentElement.clientHeight - 265;
          } else {
            this.maxheight = "auto";
          }
          this.pageNum1 = result.data.pagination.page * 1;
          this.totalListNum1 = result.data.pagination.total * 1;
          this.pageSize1 = result.data.pagination.page_size * 1;
        } else {
          this.$message({
            type: "error",
            message: result.message,
          });
        }
      } else {
        let result = await reqCarrierSummaryList({
          branch_id: String(searchCarrierData.bigArea), //区域
          carrier_id: String(searchCarrierData.carrier_id), //承运商id
          start_time: String(parseInt(searchCarrierData.createTime[0] / 1000)),
          end_time: String(parseInt(searchCarrierData.createTime[1] / 1000)),
          page: String(pageNum2),
          page_size: String(pageSize2),
        });
        if (result.code === 10000) {
          // // console.log("刷新承运商列表");
          this.carrierTableData = result.data.data || [];
          if (this.carrierTableData.length > 6) {
            //一排操作栏
            this.maxheight = document.documentElement.clientHeight - 245;
          } else {
            this.maxheight = "auto";
          }
          this.pageNum2 = result.data.pagination.page * 1;
          this.totalListNum2 = result.data.pagination.total * 1;
          this.pageSize2 = result.data.pagination.page_size * 1;
        } else {
          this.$message({
            type: "error",
            message: result.message,
          });
        }
      }
    },
    resettingData() {
      Object.assign(
        this.$data.searchCustomerData,
        this.$options.data().searchCustomerData
      );
      Object.assign(
        this.$data.searchCarrierData,
        this.$options.data().searchCarrierData
      );
      this.displayOrders();
    },
    lastMonthTimetamp() {
      //  一天的秒数
      const MillisecondsADay = 24 * 60 * 60;

      const date = new Date();
      date.setDate(1);
      date.setHours(0, 0, 0, 0);
      //  当月开始时间戳
      const timeStamp = date.getTime() / 1000;
      //  上个月的天数
      const days = this.lastMonthDats();
      //  上月开始时间戳
      const lastMonthStart = timeStamp - MillisecondsADay * days;
      //  上月结束时间戳
      const lastMonthEnd = timeStamp - 1;
      this.searchCustomerData.createTime = [
        lastMonthStart * 1000,
        lastMonthEnd * 1000,
      ];
      this.searchCarrierData.createTime = [
        lastMonthStart * 1000,
        lastMonthEnd * 1000,
      ];
    },
    lastMonthDats() {
      const date = new Date();
      const year = date.getFullYear();
      //  上个月月份
      let month = date.getMonth() + 1 - 1; //  0-11 表示 1月-12月
      //  0 表示12月
      month = month || 12;
      //  30天的月份
      const arr30 = [4, 6, 9, 11];
      //  31天的月份
      const arr31 = [1, 3, 5, 7, 8, 10, 12];
      if (arr30.indexOf(month) !== -1) {
        //  上个月是 30 天
        return 30;
      } else if (arr31.indexOf(month) !== -1) {
        //  上个月是 31 天
        return 31;
      } else {
        //  2月
        if (this.isRunYear(year)) {
          return 29;
        } else {
          return 28;
        }
      }
    },
    isRunYear(year) {
      //  条件:能被4整除并且不能被100整除，或者被400整除的
      let flag = false;
      if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
        flag = true;
      }
      return flag;
    },
    async getCustomerList() {
      this.customerList = this.$store.getters.customerList;
    },
    async getCarrierList() {
      this.carrierList = this.$store.getters.carrierList;
    },
    async getBigAreaList() {
      this.bigAreaList = this.$store.getters.websiteList;
    },
    async getSalesList() {
      this.salesList = this.$store.getters.adminList;
    },
    handleClick() {
      //切换客户和承运商
      this.displayOrders();
    },
    searchCheckList() {
      this.displayOrders();
    },
    handleSizeChange1(val) {
      this.pageSize1 = val; //一页多少条
      this.displayOrders();
    },
    handleCurrentChange1(val) {
      this.pageNum1 = val; //第多少页
      this.displayOrders();
    },
    handleSizeChange2(val) {
      this.pageSize2 = val; //一页多少条
      this.displayOrders();
    },
    handleCurrentChange2(val) {
      this.pageNum2 = val; //第多少页
      this.displayOrders();
    },
    handleSelectionChange(checked) {
      this.selectedOrders = checked.map((item) => item.id);
    },
    async clickToDetail(id, area, time) {
      //点击去对应的详情
      if (this.activeName === "first") {
        this.customer_detail_no = id;
        this.bigArea_detail_no = area;
        this.customer_detail_time = time;
        this.operationType = true;
        this.showCustomerDetail = true;
      } else {
        this.carrier_detail_no = id;
        this.carrier_detail_time = time;
        this.operationType = true;
        this.showCarrierDetail = true;
      }
    },
    //控制详情页的显示隐藏
    changeCustomerDetailPage(val) {
      this.showCustomerDetail = val;
    },
    changeCarrierDetailPage(val) {
      this.showCarrierDetail = val;
    },
    isHavePermission(val) {
      return isHavePermission(val);
    },
  },
};
</script>

<style lang="less" scoped>

.tab.el-tabs--border-card {
  border: none;
  box-shadow: none;

  .el-tabs__content {
    padding: 0;
    height: 40px;
  }
}
.operation {
    /* background: red; */
    text-align: end;
  }
.allOrderContainer {
/* 
  margin-left: 5px;
  background-color: #fff; */
}
.shareContainer {
  background-color: #fff;

  .el-form-item--mini.el-form-item {
    margin-bottom: 10px;
  }
 
}
</style>
